<?php

namespace App\Http\Controllers;

use App\Http\Requests\Backend\LoginRequest;
use App\Http\Requests\Backend\ResetRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @param LoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(LoginRequest $request)
    {
        $credentials = request(['email', 'password']);

        if (!$token = auth()->attempt($credentials)) {
            return responseResult([], self::ERROR_CODE, ' 账号密码错误');
        }
        $token = $this->respondWithToken($token);
        $user_info = array_only(auth()->user()->toArray(), ['name', 'email', 'avatar']);
        return responseResult(compact('token', 'user_info'));
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return responseResult(array_only(auth()->user()->toArray(), ['name', 'email', 'avatar']));
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return responseResult([], 0, '退出成功');
    }

    /**
     * Reset password
     *
     * @param ResetRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword(ResetRequest $request)
    {
        $oldPwd = $request->get('oldpwd');
        $check = User::where('id', auth()->id())->first();
        if (!Hash::check($oldPwd, $check->password)) {
            return responseResult([], 1, '原密码不正确');
        }
        $update['password'] = Hash::make($request->get('pwd'));
        $result = User::where('id', auth()->id())->update($update);
        return responseResult($this->respondWithToken(auth()->refresh()), $result ? 0 : 1, '修改成功');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return responseResult($this->respondWithToken(auth()->refresh()));
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return array $token
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ];
    }
}
